package chances.wechat.listener;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import chances.framework.ufs.UserDirectory;
import chances.framework.ufs.UserFileSystem;
import chances.wechat.entity.WechatUser;
import chances.wechat.service.WechatUserService;

@Component
public class LoginListener {

    private ExecutorService pool = Executors.newFixedThreadPool(5);
    @Autowired
    private WechatUserService userService;

    private static Logger userLogger = LoggerFactory.getLogger("userLogger");

    // @Autowired
    // TokenFactory tokenFactory;
    @Autowired
    UserFileSystem userFileSystem;

    public WechatUser getWechatUser(String appCode, String openId, String type,
            String token) {
        // TokenSet tokenSet = tokenFactory.getTokenSet(appCode);
        //
        // OauthAPI oauthAPI = new OauthAPI(tokenSet.getAppId(),
        // tokenSet.getSecret());
        // String accessToken = tokenSet.getAccessToken();
        // WechatUser wechatUser = this.userService.getWechatUser(openId);
        // if (wechatUser == null) {
        // Map<String, Object> userInfo = null;
        // if (WechatConstant.LOGIN_BASE.equals(type)) {
        // userInfo = oauthAPI.getUserInfo(accessToken, openId);
        // } else {
        // userInfo = oauthAPI.getSnsUserInfo(token, openId);
        // }
        // Object errorCode = userInfo.get("errcode");
        // if (errorCode == null) {
        // wechatUser = this.toWechatUser(userInfo);
        // this.userService.insertWeixinUser(wechatUser);
        // saveUserIcon(wechatUser);
        // }
        // } else {
        // this.userService.updateWeixinUserLoginTime(openId);
        // saveUserIcon(wechatUser);
        // }
        // return wechatUser;
        return null;
    }

    private WechatUser toWechatUser(Map<String, Object> userInfo) {
        WechatUser wechatUser = new WechatUser();
        wechatUser.setSex(Integer.parseInt(userInfo.get("sex") + ""));
        Date subTime = new Date();
        String subscribetime = userInfo.get("subscribetime") + "";
        if (StringUtils.isNotEmpty(subscribetime)
                && !subscribetime.equals("null")) {
            subTime.setTime(Long.parseLong(subscribetime));
        }
        wechatUser.setSubTime(subTime);
        wechatUser.setStatus(WechatUser.ENABLE_STATUS);
        wechatUser.setUnionId(userInfo.get("unionid") + "");
        String city = userInfo.get("city") + "," + userInfo.get("province")
                + "," + userInfo.get("country");
        wechatUser.setCity(city);
        wechatUser.setLang(userInfo.get("language") + "");
        wechatUser.setOpenId(userInfo.get("openid") + "");
        wechatUser.setAvator(userInfo.get("headimgurl") + "");
        String nickname = userInfo.get("nickname") + "";
        try {
            userLogger.info("openid:" + wechatUser.getOpenId() + ",nickName:"
                    + wechatUser.getNickname());
            nickname = URLEncoder.encode(nickname, "UTF-8");
            userLogger.info("utf-8 nickName:" + nickname);
        } catch (UnsupportedEncodingException e) {

        }
        wechatUser.setNickname(nickname);
        return wechatUser;
    }

    public void saveUserIcon(WechatUser wechatUser) {
        this.pool.execute(new Runnable() {

            @Override
            public void run() {
                UserDirectory userDirectory = userFileSystem
                        .getUserDirectory(wechatUser.getOpenId());
                try {
                    userDirectory.saveFromUrl("user_icon.jpg",
                            new URL(wechatUser.getAvator()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

}
